package org.example.config;

import jakarta.servlet.DispatcherType;
import jakarta.servlet.Filter;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.ContentCachingRequestWrapper;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    }


//    @Bean
//    public FilterRegistrationBean<CorsFilter> corsFilter() {
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/**", corsConfig());
//
//        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
//        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
//        return bean;
//    }

    @Bean
    public CorsConfiguration corsConfig() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern(CorsConfiguration.ALL);
        config.addAllowedMethod(CorsConfiguration.ALL);
        config.addAllowedHeader(CorsConfiguration.ALL);
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);
        return config;
    }

    @Bean
    public FilterRegistrationBean<Filter> contentCachingRequestWrapperFilter() {
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>((request, response, chain) -> chain.doFilter(needWrap(request) ? new ContentCachingRequestWrapper((HttpServletRequest) request) : request, response));
        bean.setOrder(Ordered.LOWEST_PRECEDENCE);
        return bean;
    }

    private static boolean needWrap(ServletRequest request) {
        if (DispatcherType.ASYNC != request.getDispatcherType()) {
            String contentType = request.getContentType();
            return contentType != null && (contentType.regionMatches(true, 0, MediaType.APPLICATION_JSON_VALUE, 0, MediaType.APPLICATION_JSON_VALUE.length()) ||
                    contentType.regionMatches(true, 0, MediaType.APPLICATION_FORM_URLENCODED_VALUE, 0, MediaType.APPLICATION_FORM_URLENCODED_VALUE.length()));
        }
        return false;
    }
}